package cn.roadtrip.utilupload;

import cn.hutool.core.date.DateUtil;
import cn.roadtrip.utilmodule.util.DataBean;
import cn.roadtrip.utilmodule.util.oss.OSSImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

@RestController
@Slf4j
public class UploadFileController {
    public static final String UPLOADED_FOLDER = System.getProperty("user.dir") + File.separator + "uploadFile";

    private OSSImpl ossImpl;

    public UploadFileController(OSSImpl ossImpl) {
        log.info("UploadFileController init");
        this.ossImpl = ossImpl;
    }

    @PostMapping("/ul/uploadFile")
    public DataBean uploadFile(
            @RequestParam("file") MultipartFile multipartFile
    ) {
//上传并保存临时文件

        String subPath = DateUtil.format(new Date(System.currentTimeMillis()), "yyyyMM") + File.separator + DateUtil.format(new Date(System.currentTimeMillis()), "dd");
        java.io.File path = new java.io.File(UPLOADED_FOLDER, subPath);
//        System.out.println("path->" + path.getAbsolutePath());
        path.mkdirs();
//        System.out.println("filename->" + multipartFile.getName() + "\torigFilename->" + multipartFile.getOriginalFilename());
        String contentType = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        String uuid = java.util.UUID.randomUUID().toString();
        String fileName = uuid + contentType;
        File fouFile = new File(path, fileName);
        try (BufferedInputStream fileInputStream = new BufferedInputStream(multipartFile.getInputStream())) {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
//            System.out.println("-->" + path + File.separator + fileName);
            byte[] bs = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bs)) != -1) {
                bos.write(bs, 0, len);
            }
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
            return DataBean.err("err", e.getMessage());
        }

        Timer timer = new Timer();
        //定时删除上传文件
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    fouFile.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 30 * 60 * 1000l);//延时30分钟执行
        //上传到oss
        return ossImpl.uploadFile(fouFile);
    }
}
